package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.sql.SqlBuilder;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.temporary.TemporaryWmNews;
import com.heima.model.wemeda.dto.WmNewsDto;
import com.heima.model.wemeda.dto.WmNewsPageReqDto;
import com.heima.model.wemeda.entity.WmMaterial;
import com.heima.model.wemeda.entity.WmNews;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.dao.WmMaterialDao;
import com.heima.wemedia.dao.WmNewsDao;
import com.heima.wemedia.dao.WmNewsMaterialDao;
import com.heima.wemedia.service.WmNewsService;
import net.sf.jsqlparser.statement.select.Join;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 15:48:07
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsDao wmNewsDao;
    @Autowired
    private WmMaterialDao wmMaterialDao;

    @Autowired
    private WmNewsMaterialDao wmNewsMaterialDao;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult queryPage(WmNewsPageReqDto wmNewsDto) {
        if (wmNewsDao == null) {
            return PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        wmNewsDto.checkParam();
        //2. 封装查询条件
        Map<String, Object> queryParam = BeanUtil.beanToMap(wmNewsDto);
        queryParam.put("userId", WmThreadLocalUtil.get());
        //3. 执行查询
        PageHelper.startPage(wmNewsDto.getPage(), wmNewsDto.getSize());
        Page<WmNews> page = wmNewsDao.queryByMap(queryParam);
        PageResponseResult pageResponseResult = new PageResponseResult(page.getPageNum(), page.getPageSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getResult());
        return pageResponseResult;
    }


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ResponseResult queryById(Long id) {
        WmNews wmNews = this.wmNewsDao.queryById(id);
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 分页查询
     *
     * @param wmNews      筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */

    /**
     * 新增数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews insert(WmNews wmNews) {
        this.wmNewsDao.insert(wmNews);
        return wmNews;
    }


    //添加文章和文章素材关系表数据
    @Override
    public ResponseResult addNewsAndNewsMaterial(WmNewsDto wmNewsDto) {
        if (wmNewsDto == null || wmNewsDto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //new实体类        dto实体类
        // String images  展示图片    List<String> images
        // enable是否上架
        // content文章内容  content文章内容
        // integer type 布局类型    short type
        // integer status文章状态    short status

        //将展示照片从集合取出转换为String字符串用,分隔
        List<String> covenimages = wmNewsDto.getImages();
        //数据补全
        Long userId = WmThreadLocalUtil.get();
        wmNews.setUserId(userId);
        wmNews.setCreatedTime(new Date());
        wmNews.setUpdatedTime(new Date());
        //前端传过来的状态为-1,按逻辑取照片数量
        String content = wmNewsDto.getContent();//获得文章数据(图片/文本)
        //文章数据转换为map集合
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //取出文章里的内容图片
        List<String> contentImages = mapList.stream().filter(map -> "image".equals(map.get("type"))).map(map -> map.get("value").toString()).collect(Collectors.toList());
        //内容图片集合转换为字符串
        String ResultCollect = contentImages.stream().map(String::valueOf).collect(Collectors.joining(","));
        wmNews.setImages(ResultCollect);
        //        大于等于3   取三张    大于0   取一张    等等0  不取
        if (wmNewsDto.getType() == -1) {
            if (contentImages.size() >= 3) {
                covenimages = contentImages.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(3);
            } else if (contentImages.size() > 0) {
                covenimages = contentImages.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(1);
            } else {
                covenimages = Collections.emptyList();
                wmNews.setType(0);
            }
        }
        //执行添加或者修改方法
        String covenimage = covenimages.stream().map(String::valueOf).collect(Collectors.joining(","));
        wmNews.setImages(covenimage);//展示图片(如果类型不为自动直接存,类型为自动存内容里的图片)
        this.saveOrUpdate(wmNews); //保存文章
        //保存文章素材关系表(图片/内容)
        saveCovenimages(wmNews, covenimages);
        saveContentImages(wmNews, contentImages);
        //发送消息到broker中
        kafkaTemplate.send("news.check.topic",wmNews.getId()+"");
        return ResponseResult.okResult("添加成功");
    }

    //保存内容相关素材
    private void saveContentImages(WmNews wmNews, List<String> contentImages) {

        saveWmNewsMaterial(wmNews, contentImages, 0);
    }
    private void saveWmNewsMaterial(WmNews wmNews, List<String> contentImages, int type) {
        if (StringUtils.isEmpty(contentImages)) {
            return;
        }
        //保存素材相关信息
        List<WmMaterial> wmMaterials = wmMaterialDao.queryByUrls(contentImages);
        List<String> collect = contentImages.stream().distinct().collect(Collectors.toList());
        //得到素材表的ids
        List<Long> materialIds = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
        //前端提交把素材放到上传中没有上传  删了素材再上传
        if (collect.size() != contentImages.size()) {
            throw new RuntimeException("素材缺失");
        }
        Long newsId = wmNews.getId();
        //materialIds素材id,文章id,类型
        wmNewsMaterialDao.saveAllByIds(materialIds, newsId, type);
    }

    //保存内容相关素材展示相关素材
    private void saveCovenimages(WmNews wmNews, List<String> covenimages) {
        saveWmNewsMaterial(wmNews, covenimages, 1);
    }


    //执行添加或者修改操作
    private void saveOrUpdate(WmNews wmNews) {

        //添加
        if (wmNews.getId() == null) {
            wmNews.setEnable(1);
            wmNewsDao.save(wmNews);
            return;
        }
        //修改
        wmNewsDao.update(wmNews);
        wmNewsMaterialDao.deleteById(wmNews.getId());

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResponseResult deleteById(Long id) {
        wmNewsDao.deleteById(id);
        wmNewsMaterialDao.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }
}
